package com.citydo.webrtcspringboot.transfer.udp.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.citydo.webrtcspringboot.GlobalConfig;
import com.citydo.webrtcspringboot.MessageType;
import com.citydo.webrtcspringboot.component.ThreadPool;
import com.citydo.webrtcspringboot.transfer.udp.UdpClient;
import com.citydo.webrtcspringboot.transfer.udp.UdpServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

//发送UDP的服务
@Slf4j
@Service
public class UdpService {
    private final ResourceLoader resourceLoader;
    //汽轮机转速模拟量
    private JSONArray STRImitate;
    private int currentImitateIndex = 0;
    private long currentTime = 0;
    private UdpClient udpClient;
    private int speed = 0;

    @Autowired
    public UdpService(UdpClient udpClient, ResourceLoader resourceLoader) throws IOException {
        this.udpClient = udpClient;
        SendUdp();
        this.resourceLoader = resourceLoader;
        STRImitate = JSON.parseArray(JsonReader("极热态.json"));
    }

    public void SendUdp() {
//        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        // 创建一个定时任务
        Runnable task = () -> {
            try {
                if (!GlobalConfig.StartImitate) {
                    if(currentImitateIndex != 0)
                        log.info("停止模拟");
                    currentImitateIndex = 0;
                    speed = 0;
                    currentTime = 0;
                    return;
                }
                if (currentImitateIndex == 0) {
                    log.info("开始模拟");
                }
//                udpClient.SendUdp("{time:1,speed:"+(speed)+"}");
//                SteamRotation rotation = new SteamRotation();
//                rotation.mode = UdpServer.CurrentMode;
//                rotation.AD.add(1.23f);
//                rotation.AD.add(1.67f);
//                rotation.AD.add(1.445f);
//                rotation.AD.add((float)speed++);
//                udpClient.SendUdp("{AD:["+","+(speed++)+"]}");
//                udpClient.SendUdp("{AD:[1.23,1.67,1.445]}");

                JSONObject object = JSON.parseObject(STRImitate.get(currentImitateIndex>=STRImitate.size()?currentImitateIndex-1:currentImitateIndex++).toString());
                currentTime++;
                JSONObject sendObj = new JSONObject();
                float rate = 0;
                List<Float> rates = new ArrayList<>();
                Object o = object.get("rate");
                if (o.getClass() == String.class) {
                    rate = Float.parseFloat((String) o);
                } else {
                    rate = (Float) o;
                }
                sendObj.put("AD", GenerateRandomAD(rate));
                sendObj.put("mode", UdpServer.CurrentMode);
                sendObj.put("time",currentTime);
                sendObj.put("imitate",true);
                udpClient.SendUdp(sendObj.toJSONString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        // 定时任务延迟2秒后开始执行，然后每隔1秒执行一次
        ThreadPool.Instance.scheduler.scheduleAtFixedRate(task, 2, 1, TimeUnit.SECONDS);
    }

    public String JsonReader(String fileName) throws IOException {
        Resource resource = resourceLoader.getResource("classpath:static/" + fileName);
        BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }

    private List<Float> GenerateRandomAD(float rate) {
        List<Float> list = new ArrayList<>();
        list.add(rate);
        for (int i = 0; i < 7; i++) {
            //创建一个1-10的随机数
            rate = (float) (Math.random() * 5);
            list.add(rate);
        }
        return list;
    }
}
